package com.mars.boss.weixin.web.contrller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import com.mars.boss.weixin.wx.handler.WeixinHandler;
import com.mars.boss.weixin.wx.utils.WeixinConstant;
import com.mars.common.utils.FileUtil;
import com.mars.common.utils.RandomUitl;
import com.mars.common.utils.WebUtil;
import com.mars.common.utils.security.SecurityUtils;
import com.mars.web.common.support.BaseController;

@Controller
@RequestMapping("/weixin")
public class WeixinController extends BaseController {

	private static final String TOKEN = WeixinConstant.TOKEN ;
	
	/**
	 * 微信接入
	 * @param request
	 * @param response
	 */
	@RequestMapping(method=RequestMethod.GET)
	public void connect(HttpServletRequest request, HttpServletResponse response) {
		try {
			logger.info("RemoteAddr: "+ request.getRemoteAddr());  
			logger.info("QueryString: "+ request.getQueryString());  
	        
			//接收微信发送过来的参数
			String signature = request.getParameter("signature");	// 微信加密签名  
			String timestamp = request.getParameter("timestamp");	// 时间戳  
			String nonce = request.getParameter("nonce");			// 随机数  
			String echostr = request.getParameter("echostr");		// 随机字符串  
			
			//1. 将token、timestamp、nonce三个参数进行字典序排序  
			String[] str = { TOKEN, timestamp, nonce };  
			Arrays.sort(str); 
			
			//2. 将三个参数字符串拼接成一个字符串进行sha1加密  
			String digest = SecurityUtils.sha1(str[0] + str[1] + str[2]);  
	        
			//3. 确认请求来至微信  
			if (digest.equals(signature)) {  
				//完成相互认证
			    response.getWriter().write(echostr);  
			    logger.info("微信服务器接入生效..........");  
			} else {
				logger.info("微信服务器接入失败..........");  
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}  
	}
	
	@RequestMapping(method=RequestMethod.POST)
	public void wexinMessageHandler(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 将请求、响应的编码均设置为UTF-8（防止中文乱码）  
        request.setCharacterEncoding("UTF-8");  
        response.setCharacterEncoding("UTF-8"); 
        
        // 调用核心业务类接收消息、处理消息  
        String respMessage = WeixinHandler.processRequest(request);  
          
        // 响应消息  
        PrintWriter out = response.getWriter();  
        out.print(respMessage);
        out.close(); 
	}
	
	
	@PostMapping(value="/upload")
	public Object upload(MultipartFile[] files) {
		Map<String, String> msgMap = new HashMap<String, String>() ;
		
		String contextSaveDir = "wxImage" ;
		File saveDir = FileUtil.createDir(new File(WebUtil.getRealPath(request)).getParent()+File.separator+contextSaveDir) ;
		for (MultipartFile file : files) {
			String ext = FilenameUtils.getExtension(file.getOriginalFilename()) ;
			String baseName = FilenameUtils.getBaseName(file.getOriginalFilename()) ;
			String filename = RandomUitl.uuid()+"."+ext ;
			String destination = saveDir.getPath()+File.separator+filename ;
			String viewUrl = WebUtil.getDomain(request) + contextSaveDir + "/" + filename ;
			try {
				FileUtils.copyInputStreamToFile(file.getInputStream(), new File(destination));
			} catch (IOException e) {
				return setResponseResultFailed("上传文件失败：" + baseName) ;
			}
			
			msgMap.put("fileName", filename) ;
			msgMap.put("baseUrl", "/" + contextSaveDir + "/" +filename) ;
			msgMap.put("fullUrl", viewUrl) ;
			logger.info("文件上传成功：[文件名称：{}, URL地址：{}]", filename, viewUrl);
		}
		return setResponseResultOk(msgMap) ;
	}
	
}
